package com.chenu.pvcstumansys.service.impl;

import com.chenu.pvcstumansys.db.bean.Message;
import com.chenu.pvcstumansys.db.mapper.MessageMapper;
import com.chenu.pvcstumansys.service.MessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * 消息服务实现
 */
@Service(value = "messageService")
public class MessageServiceImpl implements MessageService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 以下是系统可提供服务的所有索引号
     * 每添加一个新的服务，都需要在这里添加上索引号
     */
    public static final int USER_SERVER = 0;      /* 用户服务索引号 */

    /**
     * 请求服务消息的路由键
     */
    public static final String SERVICE_ROUTING_KEY = "service";


    @Autowired
    private MessageMapper messageMapper;

    @Override
    public int remove(Integer pUid) {
        return messageMapper.deleteByPrimaryKey(pUid);
    }

    @Override
    public int save(Message record) {
        return messageMapper.insertSelective(record);
    }

    @Override
    public Message findById(Integer pUid) {
        return messageMapper.selectByPrimaryKey(pUid);
    }

    @Override
    public int update(Message record) {
        return messageMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public Message sendAndReceive(Message message, int toService) {
        // 根据索引号，发送消息给对应的服务
        // 服务完成后，得到返回消息
        switch (toService){
            case USER_SERVER:                 /* 用户服务 */
                logger.info("你请求了一个用户服务...");
                return (Message) rabbitTemplate.convertSendAndReceive(
                        UserServiceImpl.EXCHANGES,
                        SERVICE_ROUTING_KEY,
                        message
                );

            default:
                logger.warn("你请求了一个不存在的服务...");
                return null;
        }
    }
}
